<template>
    <el-container style="border: solid 1px #5D7DB3; margin: 35px;">
        <el-header style="background-color: #5D7DB3; display: flex; align-items: center; margin-bottom: 20px;">
            <div class="title">
                <span>用户管理</span>
            </div>
        </el-header>
        <div>
            <el-main>
                <el-row :gutter="40">
                    <el-col :span="4">
                        <!-- 添加用户按钮 -->
                        <el-button style="background-color: #5D7DB3; border:none;" class="add" type="success"
                            icon="el-icon-plus" @click="showAddDialog">添加</el-button>
                    </el-col>
                </el-row>
                <el-table :data="currentUserTableData" border stripe @row-click="handleRowClick"
                    :row-class-name="highlightRow">
                    <el-table-column prop="name" label="用户"></el-table-column>
                    <el-table-column prop="password" label="密码" :formatter="formatPassword"></el-table-column>
                    <el-table-column prop="permissions" label="权限"></el-table-column>
                    <el-table-column prop="department" label="部门"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="success" @click="openEditDialog(scope.row)">编辑 <i class="el-icon-edit"></i>
                            </el-button>
                            <el-button type="danger" @click="handleDelete(scope.row)">删除 <i
                                    class="el-icon-remove-outline"></i></el-button>
                        </template>
                    </el-table-column>

                </el-table>
            </el-main>

            <!-- 添加用户的弹窗 -->
            <el-dialog title="添加部门" :visible.sync="addDialogVisible" width="30%" @close="resetForm">
                <el-form :model="form" ref="form" :rules="rules" label-width="100px">
                    <el-form-item label="用户" prop="name">
                        <el-input v-model="form.name" placeholder="请输入用户"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="form.password" placeholder="请输入密码" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="confirmPassword">
                        <el-input type="password" v-model="form.confirmPassword" placeholder="请再次输入密码"
                            show-password></el-input>
                    </el-form-item>
                    <el-form-item label="权限" prop="permissions">
                        <el-select v-model="form.permissions" placeholder="请选择权限">
                            <el-option v-for="item in options1" :key="item.value1" :label="item.label1"
                                :value="item.label1">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="部门" prop="department">
                        <el-select v-model="form.department" placeholder="请选择">
                            <el-option v-for="item in options2" :key="item.value2" :label="item.label2"
                                :value="item.label2">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click=" addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </div>
            </el-dialog>
            <!-- 编辑行弹窗 -->
            <el-dialog :visible.sync="editDialogVisible" title="编辑" width="30%">
                <el-form :model="editForm" :rules="rules" label-width="100px">
                    <el-form-item label="用户" prop="name">
                        <el-input v-model="editForm.name" placeholder="请输入用户"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="editForm.password" placeholder="请输入密码"
                            show-password></el-input>
                    </el-form-item>
                    <el-form-item label="权限" prop="permissions">
                        <el-select v-model="editForm.permissions" placeholder="请选择权限">
                            <el-option v-for="item in options1" :key="item.value1" :label="item.label1"
                                :value="item.label1">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="部门" prop="department">
                        <el-select v-model="editForm.department" placeholder="请选择">
                            <el-option v-for="item in options2" :key="item.value2" :label="item.label2"
                                :value="item.label2">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="saveEdit">保存</el-button>
                        <el-button @click="editDialogVisible = false">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
        <el-footer>
            <el-pagination class="UserPage" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="userTableData.length">
            </el-pagination>
        </el-footer>
    </el-container>
</template>

<script>
import axios from 'axios';
export default {
    data() {
        return {
            userTableData: [],
            options1: [{
                value1: '选项1',
                label1: '0'
            }, {
                value1: '选项2',
                label1: '1'
            }],
            options2: [{
                value2: '选项1',
                label2: '1'
            }, {
                value2: '选项2',
                label2: '2'
            }, {
                value2: '选项3',
                label2: '3'
            }],
            currentPage: 1,
            pageSize: 10,
            value1: '',
            value2: '',
            selectedRow: null,
            addDialogVisible: false,
            editDialogVisible: false,
            watch: {
                'form.permissions': function (newValue) {
                    const selectedOption = this.options.find(option => option.value === newValue);
                    this.userTableData = [{ permissions: selectedOption ? selectedOption.label : '' }];
                },
            },
            editForm: {
                name: '',
                password: '',
                permissions: '',
                department: '',
            },
            form: {
                name: '',
                password: '',
                permissions: '',
                confirmPassword: '',
                department: '',
            },
            rules: {
                name: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/, message: '密码必须是数字和字母的组合，且至少包含8个字符', trigger: 'blur' }
                ],
                confirmPassword: [
                    { required: true, message: '请再次输入密码', trigger: 'blur' },
                    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/, message: '密码必须是数字和字母的组合，且至少包含8个字符', trigger: 'blur' }
                ],
                permissions: [
                    { required: true, message: '请选择权限', trigger: 'blur' }
                ],
                department: [
                    { required: true, message: '请输入部门', trigger: 'blur' }
                ]
            }
        };
    },
    computed: {
        // 计算当前页的数据
        currentUserTableData() {
            const startIndex = (this.currentPage - 1) * this.pageSize;
            const endIndex = startIndex + this.pageSize;
            return this.userTableData.slice(startIndex, endIndex);
        }
    },
    created() {
        this.fetchUsers();
    },
    methods: {
        // 分页大小变化时的回调
        handleSizeChange(val) {
            this.pageSize = val;
        },
        // 当前页变化时的回调
        handleCurrentChange(val) {
            this.currentPage = val;
        },
        // 添加用户的弹窗
        showAddDialog() {
            this.addDialogVisible = true;
        },
        resetForm() {
            this.$refs.form.resetFields();
        },
        //获取全部数据
        fetchUsers() {
            axios.get('/users/getAll')
                .then(response => {
                    // 检查响应数据的结构
                    if (Array.isArray(response.data.data)) {
                        this.userTableData = response.data.data;
                    } else {
                        console.error('Invalid response format:', response.data);
                    }
                })
                .catch(error => {
                    console.error('Error fetching departments:', error);
                    this.userTableData = [];
                });
        },
        submitForm() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    // Check if passwords match
                    if (this.form.password !== this.form.confirmPassword) {
                        this.$message.error('两次输入的密码不一致');
                        return;
                    }
                    const userAddData = {
                        name: this.form.name,
                        password: this.form.password,
                        confirmPassword: this.form.confirmPassword,
                        permissions: this.form.permissions,
                        department: this.form.department
                    };
                    axios.post('/users/add', userAddData)
                        .then(response => {
                            console.log('Data successfully sent to backend:', response);
                            if (response && response.status === 200) {
                                this.userTableData.push({
                                    name: this.form.name,
                                    password: this.form.password,
                                    confirmPassword: this.form.confirmPassword,
                                    permissions: this.form.permissions,
                                    department: this.form.department
                                });
                                this.$message({
                                    type: "success",
                                    message: '添加成功'
                                });
                                this.fetchUsers();
                                this.totalItemNotice = this.userTableData.length;
                                this.currentPageNotice = this.totalPages;
                                this.addDialogVisible = false;
                                this.$refs.form.resetFields();
                            } else {
                                console.error('Error sending data to backend:', response);
                                this.$message('添加功能出现异常');
                            }
                        })
                        .catch(error => {
                            console.error('Error sending data to backend:', error);
                            this.$message('添加功能出现异常');
                        });
                }
            });
        },

        // 选中变颜色
        handleRowClick(row) {
            this.selectedRow = row; // Update the selected row data
        },
        highlightRow(row) {
            return row === this.selectedRow ? 'highlight' : '';
        },
        // 编辑按钮
        openEditDialog(row) {
            this.editDialogVisible = true;
            this.editForm.name = row.name;
            this.editForm.password = row.password;
            this.editForm.permissions = row.permissions;
            this.editForm.department = row.department;
        },
        saveEdit() {
            const rowIndex = this.userTableData.indexOf(this.selectedRow);
            this.userTableData[rowIndex].name = this.editForm.name;
            this.userTableData[rowIndex].password = this.editForm.password;
            this.userTableData[rowIndex].permissions = this.editForm.permissions;
            this.userTableData[rowIndex].department = this.editForm.department;
            // 向后端发送更新请求
            axios.put(`/users/update/${this.selectedRow.userId}`, {
                name: this.editForm.name,
                password: this.editForm.password,
                permissions: this.editForm.permissions,
                department: this.editForm.department
            })
                .then(() => {
                    this.editDialogVisible = false;
                    this.fetchUsers();
                    this.$message({
                        type: 'success',
                        message: '保存成功!'
                    });
                })
                .catch(error => {
                    console.error('Error updating department:', error);
                    this.editDialogVisible = false;
                    this.$message.error('保存用户数据时出现错误');
                });
        },

        // 删除按钮
        handleDelete(row) {
            this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.delete(`/users/delete/${row.userId}`)
                    .then(() => {
                        const index = this.userTableData.indexOf(row);
                        if (index >= 0 && index < this.userTableData.length) {
                            this.userTableData.splice(index, 1);
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                    })
                    .catch(error => {
                        console.error('Error deleting department:', error);
                        this.$message.error('删除用户时出现错误');
                    });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        formatPassword() {
            // 返回一个不可见的密码格式
            return '***';
        }
    },
};
</script>

<style>
.title {
    font-size: 30px;
    font-family: 500;
    color: aliceblue;
}

.highlight {
    background-color: lightblue;
}

.UserPage {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>